import React, { Component } from "react";
import { Form, Button, Modal, Transfer, message, Tag, Tabs, List } from "antd";
import { ShareAltOutlined, StopOutlined } from "@ant-design/icons";
import axios from "axios";
import qs from "qs";
import OrgTree from "./OrgTree";
import "../mock/user003001";
import "../mock/user003002";
import "../mock/group";
import "../mock/groupMembers";
const { TabPane } = Tabs;

export default class EnableMeeting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      addVisible: false,
      //   mockData: ["李亮", "张明", "李飞", "王培"], //职工列表
      enableMockData: [], //职工列表
      enableTargetKeys: [],
      //   hostSelectedKeys: [props.record.meetingHost],
      //   joinSelectedKeys: [props.record.meetingJoin],
      rules: [
        {
          required: false,
          message: "此项不可为空",
        },
      ],
      treeData: [],
      meetingArr: "",
      // getDataSource: props.getDataSource,
      personnelGroup: [],
    };
  }
  /**分享活动 */
  enableMeeting = () => {
    if (this.props.selectedRowKeys.length === 0) {
      message.error("没有选中数据");
      return;
    }
    let meetingArr = "";
    meetingArr += this.props.selectedRowKeys.map((id) => {
      return id;
    });
    this.setState({
      addVisible: true,
      meetingArr: meetingArr,
    });

    // axios
    //   .post("../weekmeeting/enableMeeting.rst", qs.stringify({ delArr: meetingArr }))
    //   .then((res) => {
    //     let response = res.data;
    //     console.log(response);
    //     if (response.resultCode === 0) {
    //       message.success("活动分享成功");
    //       this.props.getDataSource();
    //     } else {
    //       message.error("活动分享失败");
    //     }
    //   })
    //   .catch((error) => {
    //     console.log(error);
    //     message.error("活动分享失败");
    //   });
  };
  /**禁用活动 */
  disableMeeting = () => {
    if (this.props.selectedRowKeys.length === 0) {
      message.error("没有选中数据");
      return;
    }
    let meetingArr = "";
    meetingArr += this.props.selectedRowKeys.map((id) => {
      return id;
    });

    axios
      .post(
        "../weekmeeting/disableMeeting.rst",
        qs.stringify({ delArr: meetingArr })
      )
      .then((res) => {
        let response = res.data;
        console.log(response);
        if (response.resultCode === 0) {
          message.success("活动禁用成功");
          this.props.getDataSource();
        } else {
          message.error("活动禁用失败");
        }
      })
      .catch((error) => {
        console.log(error);
        message.error("活动禁用失败");
      });
  };

  /**添加参会人 */
  handleEnableChange = (enableTargetKeys) => {
    this.setState({ enableTargetKeys });
  };
  /**机构数据 */
  setTreeData = (treeData) => {
    setTimeout(() => {
      this.setState({ treeData });
    }, 0);
  };
  /*点击部门列表,展示部门人员 */
  treeOnSelect = (value) => {
    console.log(value);
    axios
      .get("../weekmeeting/searchUsers.rst?orgId=" + value[0])
      .then((res) => {
        let response = res.data;
        // response = response.data;
        console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */

          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };
  /**弹出对话框 */
  showAddModal = () => {
    console.log(this.state.enableTargetKeys);
    // const record = this.props.record;
    /**弹出 */
    this.setState({
      addVisible: true,
    });
    /**等待form渲染 */
  };
  onFinish = (values) => {
    /**表单字段在不做改动时返回时会为undefined，需要手动判断 */
    const { enableTargetKeys } = this.state;
    console.log(enableTargetKeys);
    let pass = true;
    let messCon = "";
    /**表单返回值 currVal*/
    // const currVal = this.formRef.current.getFieldsValue();
    // console.log(currVal);
    // // console.log(currVal)
    /**判断日期，地点，内容 */

    /**判断主持人和参会人 */

    if (this.state.enableTargetKeys.length === 0) {
      pass = false;
      messCon = "分享范围";
    }

    /** 分享*/
    if (pass) {
      this.setState({ loading: true });
      /**修改活动数据 */
      axios
        .post(
          "../weekmeeting/enableMeeting.rst",
          qs.stringify({
            delArr: this.state.meetingArr,
            enable: 1,
            person: enableTargetKeys.join(),
          })
        )
        .then((res) => {
          let response = res.data;
          console.log(response);
          if (response.resultCode === 0) {
            message.success("活动分享成功");
            this.props.getDataSource();
          } else {
            message.error("活动分享失败");
          }
        })
        .catch((error) => {
          console.log(error);
          message.error("活动分享失败");
        });
    } else {
      /**有字段为空 */
      message.error(messCon + "字段不可为空！");
    }
  };

  handleCancel = () => {
    // const { enable } = this.props.record;
    /**清空修改表单状态 */
    // this.formRef.current.resetFields();
    this.setState({
      enableTargetKeys: [],
    });
    this.setState({ loading: false, addVisible: false });
  };
  /**关闭Tag */
  handleEnableTagClose = (removedTag) => {
    const enableTargetKeys = this.state.enableTargetKeys.filter(
      (enableTargetKeys) => enableTargetKeys !== removedTag
    );
    console.log(enableTargetKeys);
    this.setState({ enableTargetKeys });
  };
  /*遍历插入Tag */
  enableForMap = (tag) => {
    // console.log(tag);
    return (
      <span key={tag} style={{ display: "inline-block", marginBottom: 16 }}>
        <Tag
          closable
          color="blue"
          onClose={(e) => {
            e.preventDefault();
            this.handleEnableTagClose(tag);
          }}
        >
          {tag}
        </Tag>
      </span>
    );
  };

  /*获取人员组数据 */
  getPersonnelGroup = () => {
    axios
      .get("../weekmeeting/group.rst")
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            personnelGroup: res.map((group) => {
              return {
                label: group.groupName,
                value: group.groupName,
                groupId: group.groupId,
              };
            }),
          });
        } else {
          // message.error("人员组请求失败");
        }
      })
      .catch((error) => {
        message.error("人员组请求失败");
      });
  };

  /**选择人员组 */
  personnelGroupOnClick = (item) => {
    // console.log(item.member);
    axios
      .get("../weekmeeting/groupMembers.rst?groupId=" + item.groupId)
      .then((res) => {
        let response = res.data;
        // console.log(response);
        if (response.resultCode === 0) {
          let res = response.result.data;
          if (response.result.total === 0) {
            res = [];
          }
          /**清空并关闭添加表单 */
          this.setState({
            enableMockData: res.map((person) => {
              return {
                key: person.EMPID + "_" + person.EMPNAME,
                title: person.EMPID + "_" + person.EMPNAME,
              };
            }),
          });
        } else {
          // message.error("人员数据请求失败");
        }
      })
      .catch((error) => {
        message.error("人员数据请求失败");
      });
  };

  componentDidMount() {
    this.getPersonnelGroup();
  }

  render() {
    /**添加活动数据 */
    const {
      addVisible,
      loading,
      rules,
      enableMockData,
      enableTargetKeys,
      treeData,
      personnelGroup,
    } = this.state;
    const enableTag = enableTargetKeys.map(this.enableForMap);

    return (
      <>
        <Button type="primary" onClick={this.enableMeeting}>
          <ShareAltOutlined />
          分享
        </Button>
        <Button type="primary" onClick={this.disableMeeting}>
          <StopOutlined />
          取消分享
        </Button>

        <Modal
          visible={addVisible}
          title="请选择分享范围"
          centered
          onCancel={this.handleCancel}
          //   onOk={this.handleAdd}
          width={1000}
          //   onCancel={this.handleCancel}
          footer={null}
        >
          <Form
            name="add-meeting"
            onFinish={this.onFinish}
            className="search-meet"
            ref={this.formRef}
          >
            <Form.Item
              name="enable"
              label=""
              rules={rules}
              className="enableSelect"
            >
              {enableTag}

              <Tabs
                defaultActiveKey="1"
                type="card"
                size="small"
                className="OrgTreeTab"
              >
                <TabPane tab="人员机构" key="1">
                  <OrgTree
                    treeData={treeData}
                    setTreeData={this.setTreeData}
                    treeOnSelect={this.treeOnSelect}
                    // isHost={false}
                  />
                </TabPane>
                <TabPane tab="人员组" key="2">
                  <List
                    className="personnelGroup"
                    size="small"
                    itemLayout="horizontal"
                    dataSource={personnelGroup}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          title={item.value}
                          member={item.member}
                          onClick={() => this.personnelGroupOnClick(item)}
                        />
                      </List.Item>
                    )}
                  />
                </TabPane>
              </Tabs>

              <Transfer
                dataSource={enableMockData}
                targetKeys={enableTargetKeys}
                // selectedKeys={joinTargetKeys}
                showSearch
                listStyle={{
                  width: 250,
                  height: 200,
                }}
                operations={["添加", "移出"]}
                onChange={this.handleEnableChange}
                render={(item) => item.title}
              />
            </Form.Item>

            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
          </Form>
        </Modal>
      </>
    );
  }
}
